﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Netbits.Common.Collections;
using Netbits.Common.Conditions;

namespace Netbits.Common.Threading
{
	/// <summary>
	/// Represents a static class that holds all created managed-threads by this application
	/// </summary>
	public static class ThreadManager
	{
		#region Private Variables

		readonly static LockedList<ThreadEntry> _Threads = new LockedList<ThreadEntry>();
		readonly static Process _MainProcess = Process.GetCurrentProcess();

		#endregion

		#region Public Properties

		/// <summary>
		/// Returns all created-managed-threads locked-enumerable list
		/// </summary>
		public static IEnumerable<ThreadEntry> Threads
		{
			get
			{
				return _Threads;
			}
		}

		/// <summary>
		/// Get the main-process thread id
		/// </summary>
		public static int ProcessId
		{
			get
			{
				return _MainProcess.Id;
			}
		}

		#endregion

		#region Public Functions

		/// <summary>
		/// Create new managed thread
		/// Auto generated thread-name "thread-{id}"
		/// </summary>
		/// <returns>The new managed thread</returns>
		public static ThreadEntry Create()
		{
			return Create( string.Empty );
		}

		/// <summary>
		/// Create new managed thread with specified name
		/// </summary>
		/// <param name="Name_">The name of this thread</param>
		/// <returns>The new managed thread</returns>
		public static ThreadEntry Create( string Name_ )
		{
			ThreadEntry te = new ThreadEntry( Name_ );
			_Threads.Add( te );
			return te;
		}

		/// <summary>
		/// Remove the specified thread.
		/// </summary>
		/// <param name="Thread_">The thread that should be removed from the list.</param>
		public static void Remove( ThreadEntry Thread_ )
		{
			Condition.Requires( Thread_, "Thread_" ).IsNotNull();
			_Threads.Remove( Thread_ );
		}

		#endregion
	}
}
